<template>
  <div>
    <!-- head -->
    <!-- <el-affix :offset="94">
      <div class="card affix-container pt15 pb14">
        <el-page-header @back="router.go(-1)">
          <template #content>
            <span class="fsize16">{{ isEdit ? "编辑菜品" : "新增菜品" }}</span>
          </template>
          <template #extra>
            <div class="foot">
              <el-button @click="router.go(-1)">取消</el-button>
              <el-button @click="onSubmit" type="primary">保存</el-button>
            </div>
          </template>
        </el-page-header>
      </div>
    </el-affix> -->
    <!-- head end -->
    <div class="card">
      <div>
        <el-page-header @back="router.go(-1)">
          <template #content>
            <span class="fsize16">{{ isEdit ? "编辑菜品" : "新增菜品" }}</span>
          </template>
          <template #extra>
            <div class="foot">
              <el-button @click="router.go(-1)">取消</el-button>
              <el-button @click="onSubmit('save')" type="primary">保存</el-button>
              <el-button @click="onSubmit('create')" type="primary">保存并新增</el-button>
            </div>
          </template>
        </el-page-header>
      </div>

      <hr style="border: 1px solid #e4e6ec" />

      <el-form :model="goodsForm" label-width="120px" :rules="rules" ref="ruleFormRef">
        <el-tabs v-model="activeName" class="demo-tabs">
          <!-- 基础信息 -->
          <el-tab-pane label="基本资料" name="first" style="min-height: 70vh">
            <!-- <h4 id="section1" class="fsize16">基础信息</h4> -->
            <el-row :gutter="20" style="">
              <!-- <col :span="12"> 原本样式是这个，用width500替换了 -->
              <div class="width500">
                <el-form-item label="菜品名称" prop="name">
                  <el-input
                    v-model="goodsForm.name"
                    placeholder="请输入菜品名称"
                    clearable
                    :disabled="!goodsForm.isModify"
                  ></el-input>
                </el-form-item>

                <el-form-item label="菜品分类" prop="foodTypeId">
                  <el-tree-select
                    class="width250"
                    v-model="goodsForm.foodTypeId"
                    :data="foodType"
                    :render-after-expand="false"
                    check-strictly
                    :disabled="!goodsForm.isModify"
                  />
                  <el-text class="ml10 pointer" type="danger" @click.stop="openCategoryDialog('新增', { appletShow: 1 })">
                    <el-icon>
                      <Plus />
                    </el-icon>
                    新增分类
                  </el-text>
                </el-form-item>
              </div>
              <div class="width500">
                <el-form-item label="菜品别名" prop="byName">
                  <el-input
                    v-model="goodsForm.byName"
                    placeholder="请输入菜品别名"
                    clearable
                    :disabled="!goodsForm.isModify"
                  ></el-input>
                </el-form-item>
                <el-form-item label="菜品类型" prop="type">
                  <el-radio-group v-model="goodsForm.type" :disabled="isEdit">
                    <el-radio-button :label="1">普通菜</el-radio-button>
                    <el-radio-button :label="2">套菜</el-radio-button>
                    <el-radio-button :label="3">线下临时菜</el-radio-button>
                    <el-radio-button :label="4">临时套菜</el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </div>
              <!-- 基础信息 end-->
              <!-- 菜品构成 -->
              <!-- <col> 原本是这个替换了-->
              <div style="width: 1200px; margin-top: -10px">
                <div class="width940">
                  <!-- width1000 -->
                  <!-- <div style=""> -->
                  <!-- <h4 id="section2" class="fsize16">菜品构成</h4> -->
                  <!-- 菜品规格 -->
                  <el-form-item label="菜品规格" prop="spec">
                    <div class="spec-table">
                      <el-table :data="goodsForm.speclist">
                        <el-table-column prop="specName" width="100" label="规格名称">
                          <template #default="scope">
                            <el-input
                              v-model="scope.row.specName"
                              placeholder="请输入"
                              controls-position="right"
                              style=""
                              :disabled="!goodsForm.isModify"
                            />
                          </template>
                        </el-table-column>
                        <el-table-column prop="posPrice" label="销售价" width="120">
                          <template #default="scope">
                            <el-input
                              v-model="scope.row.posPrice"
                              oninput="value=value.replace(/[^0-9.]/g,'')"
                              placeholder="请输入"
                              :disabled="false"
                            >
                              <template #append>
                                <div>元</div>
                              </template>
                            </el-input>
                          </template>
                        </el-table-column>

                        <el-table-column prop="vipPrice" label="会员价" width="120">
                          <template #default="scope">
                            <el-input
                              v-model="scope.row.vipPrice"
                              oninput="value=value.replace(/[^0-9.]/g,'')"
                              placeholder="请输入"
                            >
                              <template #append>
                                <div>元</div>
                              </template>
                            </el-input>
                          </template>
                        </el-table-column>

                        <!-- 配置数据结构start -->
                        <el-table-column width="120" :label="item.title" v-for="(item, index) in memberList" :key="item.id">
                          <template #default="scope">
                            <el-input
                              v-model="scope.row.gradePriceList[index].price"
                              oninput="value=value.replace(/[^0-9.]/g,'')"
                              placeholder="请输入"
                            >
                              <template #append>
                                <div>元</div>
                              </template>
                            </el-input>
                          </template>
                        </el-table-column>
                        <!-- 配置数据结构end -->

                        <el-table-column prop="purPrice" label="预估成本" width="120">
                          <template #default="scope">
                            <el-input
                              v-model="scope.row.purPrice"
                              oninput="value=value.replace(/[^0-9.]/g,'')"
                              placeholder="请输入"
                            >
                              <template #append>
                                <div>元</div>
                              </template>
                            </el-input>
                          </template>
                        </el-table-column>
                        <el-table-column width="200" prop="code" label="条形码">
                          <template #default="scope">
                            <el-input v-model="scope.row.code" placeholder="请输入" :disabled="!goodsForm.isModify" />
                          </template>
                        </el-table-column>

                        <el-table-column fixed="right" prop="specName" width="80" label="是否默认" align="center">
                          <template #default="scope">
                            <div>
                              <el-button link type="primary" v-if="scope.row.isDefault" :disabled="!goodsForm.isModify">
                                <!-- 默认 -->
                                <template #icon>
                                  <img :src="radio" alt="" style="width: 20px; height: 20px" />
                                </template>
                              </el-button>
                              <el-button
                                size="20"
                                link
                                v-else
                                @click="setSpecDefault(scope.$index)"
                                :disabled="!goodsForm.isModify"
                              >
                                <!-- 设为默认 -->
                                <template #icon>
                                  <img :src="unRadio" alt="" style="width: 20px; height: 20px" />
                                </template>
                              </el-button>
                            </div>
                          </template>
                        </el-table-column>

                        <!-- <el-table-column prop="specName" width="110" label="是否默认">
                          <template #default="scope">
                            <div class="flx-align-center">
                              <el-button class="ml10" type="primary" v-if="scope.row.isDefault" :disabled="!goodsForm.isModify">
                                默认
                              </el-button>
                              <el-button
                                class="ml10"
                                v-else
                                @click="setSpecDefault(scope.$index)"
                                :disabled="!goodsForm.isModify"
                              >
                                设为默认
                              </el-button>
                            </div>
                          </template>
                        </el-table-column> -->

                        <el-table-column fixed="right" label="操作" width="64" align="center">
                          <template #default="scope">
                            <el-button
                              :icon="Plus"
                              link
                              type="danger"
                              v-if="goodsForm.type !== 2 && goodsForm.detail.isGoods !== 2 && scope.row.isDefault"
                              @click="onAddSpecItem"
                              :disabled="!goodsForm.isModify"
                            >
                            </el-button>

                            <el-button
                              style="color"
                              :icon="Minus"
                              link
                              v-if="!scope.row.isDefault"
                              :disabled="!goodsForm.isModify"
                              type="danger"
                              @click="deleteSpecRow(scope.$index, -1)"
                            >
                            </el-button>
                          </template>
                        </el-table-column>
                      </el-table>
                    </div>
                    <!-- <el-button
                      class="mt10"
                      type="danger"
                      v-if="goodsForm.type !== 2 && goodsForm.detail.isGoods !== 2"
                      @click="onAddSpecItem"
                      :disabled="!goodsForm.isModify"
                    >
                      添加多个规格
                    </el-button> -->
                  </el-form-item>
                  <!-- 菜品规格 end -->
                  <!-- 套菜时不显示菜品做法和加料 -->
                  <div v-if="goodsForm.type === 2" style="margin-top: -10px">
                    <el-form-item label="套餐明细">
                      <div style="width: 100%">
                        <div class="flx-justify-between">
                          <div class="fsize12 text-describe-color">
                            套餐明细统计金额是按比例均摊套餐价格：单明细统计金额=(单明细执行单价/已点明细执行单价总和)*套餐实时价格
                          </div>
                          <el-button :icon="Plus" @click="addPackGroup" :disabled="!goodsForm.isModify">自定义分组</el-button>
                        </div>
                        <div class="package mt10" v-for="(pack, packIx) in goodsForm.packlist" :key="packIx">
                          <el-card shadow="never">
                            <template #header>
                              <div class="flx-justify-between">
                                <div class="flx-default">
                                  <div>
                                    <el-input
                                      v-model="pack.name"
                                      placeholder="请输入分组名称"
                                      style="width: 160px"
                                      :disabled="!goodsForm.isModify"
                                    />
                                  </div>
                                  <div class="ml10">
                                    <el-select v-model="pack.selectType" style="width: 100px" :disabled="!goodsForm.isModify">
                                      <el-option
                                        v-for="item in collocation"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                      />
                                    </el-select>
                                  </div>
                                  <div class="ml10 fsize12 text-assist-color">
                                    <div class="flx-center" v-if="pack.selectType === 1">
                                      <!-- <el-input
                                        version
                                        v-model="pack.quantityStar"
                                        oninput="value=value.replace(/[^0-9.]/g,'')"
                                        style="width: 60px"
                                        :disabled="!goodsForm.isModify"
                                      /> -->
                                      <span class="ml10 mr10">
                                        本组菜
                                        <span style="font-size: 18px; color: #f56c6c">
                                          {{ pack.quantityStar }}
                                        </span>
                                        选
                                      </span>
                                      <el-input
                                        v-model="pack.quantityEnd"
                                        oninput="value=value.replace(/[^0-9.]/g,'')"
                                        style="width: 60px"
                                        :disabled="!goodsForm.isModify"
                                      />
                                      <span class="ml10 mr10">(份)</span>
                                      <div style="margin-left: 5px; display: flex; align-items: center">
                                        <el-checkbox v-model="pack.isSelectSame" label="" :disabled="!goodsForm.isModify" />
                                        <span style="margin-left: 2px">可选相同菜品</span>
                                      </div>
                                    </div>
                                    <span v-if="pack.selectType === 3" class="fsize12">
                                      <!-- 明细数量和种类任选，用法：不限量免费菜品/加价填写后随点菜数加价 -->
                                      任选该组菜品明细中的一项
                                    </span>
                                    <!-- <span v-if="pack.selectType === 2">共有{{ pack.packdetails.length }}种菜</span> -->
                                    <span v-if="pack.selectType === 2">固定选择该组所有菜品</span>
                                  </div>
                                </div>
                                <div class="pointer">
                                  <el-button
                                    type="primary"
                                    size="small"
                                    @click="openSelectTable('菜品选择', packIx)"
                                    :disabled="!goodsForm.isModify"
                                  >
                                    <!-- <el-icon><Plus /></el-icon> -->
                                    添加菜品
                                  </el-button>
                                  <el-button
                                    size="small"
                                    type="danger"
                                    @click="delPackage(packIx)"
                                    :disabled="!goodsForm.isModify"
                                  >
                                    <!-- <el-icon><Delete /></el-icon> -->
                                    删除分组
                                  </el-button>
                                </div>
                              </div>
                            </template>
                            <div>
                              <el-table :data="pack.packdetails" border>
                                <el-table-column
                                  type="selection"
                                  width="55"
                                  v-if="pack.selectType === 1 || pack.selectType === 3"
                                />
                                <el-table-column prop="foodName" label="菜品名称" />
                                <el-table-column prop="specName" label="规格" />
                                <el-table-column prop="quantity" label="数量">
                                  <template #default="scope">
                                    <el-input v-model="scope.row.quantity" oninput="value=value.replace(/[^0-9.]/g,'')" />
                                  </template>
                                </el-table-column>
                                <el-table-column prop="setPrice" label="套餐执行单价	">
                                  <template #default="scope">
                                    <el-input v-model="scope.row.setPrice" oninput="value=value.replace(/[^0-9.]/g,'')" />
                                  </template>
                                </el-table-column>
                                <el-table-column label="操作" align="center">
                                  <template #default="scope">
                                    <el-button
                                      type="danger"
                                      @click="deleteSpecRow(scope.$index, packIx)"
                                      :disabled="!goodsForm.isModify"
                                    >
                                      删除
                                    </el-button>
                                  </template>
                                </el-table-column>
                              </el-table>
                            </div>
                          </el-card>
                          <div class="slotBtn">
                            <el-button :disabled="packIx === 0" type="primary" :icon="Top" @click="moveUp(packIx)" />
                            <el-button
                              :disabled="packIx === goodsForm.packlist.length - 1"
                              type="primary"
                              :icon="Bottom"
                              @click="moveDown(packIx)"
                            />
                          </div>
                        </div>
                      </div>
                    </el-form-item>
                  </div>
                  <!-- 套菜 end -->
                  <!-- </div> -->
                </div>
                <!-- 是否是原料start
                <el-row style="margin-top: 10px">
                  <el-col :span="6">
                    <el-form-item label="是否原料" prop="type">
                      <el-radio-group v-model="goodsForm.detail.isGoods" :disabled="isGoodsMaterial">
                        <el-radio :label="1">是</el-radio>
                        <el-radio :label="0">否</el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                  <el-col :span="18">
                    <div v-if="goodsForm.detail.isGoods" style="width: 60%">
                      <el-form-item label="原料类别" prop="detail.goodsCategoryId">
                        <div class="flx-default w100">
                          <el-tree-select
                            class="w100"
                            node-key="value"
                            v-model="goodsForm.detail.goodsCategoryId"
                            :data="waresCategory"
                            :render-after-expand="false"
                            check-strictly
                          />
                        </div>
                      </el-form-item>
                    </div>
                  </el-col>
                </el-row>
                是否是原料end -->
              </div>
              <!-- 菜品z构成 end -->
            </el-row>
            <!--其他信息 -->
            <div>
              <div id="section4" class="fsize16" style="padding-left: 20px; color: #fdc31d">其他信息</div>
              <hr color="#f4f5f8" />
              <el-row style="margin-top: 10px" :gutter="20">
                <div class="width500">
                  <!-- <el-col :span="12"> -->
                  <el-form-item label="最低折扣" prop="minDiscount">
                    <el-input-number
                      style="width: 80%"
                      class="w100"
                      v-model="goodsForm.detail.minDiscount"
                      :disabled="!goodsForm.isModify"
                      :controls="false"
                    />
                    <div class="text-describe-color">说明: 90表示9折, 即90%</div>
                  </el-form-item>

                  <el-form-item label="称重菜" prop="weighType">
                    <el-radio-group v-model="goodsForm.detail.weighType" :disabled="!goodsForm.isModify" @change="weightChange">
                      <el-radio :label="1">是</el-radio>
                      <el-radio :label="0">否</el-radio>
                    </el-radio-group>
                  </el-form-item>

                  <el-form-item label="起售数量" prop="detail.upSell">
                    <el-input-number
                      style="width: 80%"
                      class="w100"
                      v-model="goodsForm.detail.upSell"
                      :disabled="!goodsForm.isModify"
                      :controls="false"
                      :min="goodsForm.detail.weighType ? 0 : 1"
                    />
                    <div class="text-describe-color">说明: 非称重菜输入小数四舍五入提交</div>
                  </el-form-item>

                  <!-- <el-form-item label="出品部门" prop="departType">
                    <el-radio-group v-model="goodsForm.detail.departType" :disabled="!goodsForm.isModify">
                      <el-radio :label="0">与菜品分类一致</el-radio>
                      <el-radio :label="1">自定义出品部门</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="设置出品部门" prop="detail.departId" v-if="goodsForm.detail.departType === 1">
                    <el-select
                      v-model="goodsForm.detail.departId"
                      placeholder="请选择"
                      style="width: 80%"
                      :disabled="!goodsForm.isModify"
                    >
                      <el-option
                        v-for="category in departmentList"
                        :key="category.name"
                        :label="category.name"
                        :value="category.id"
                      />
                    </el-select>
                  </el-form-item> -->
                </div>
                <div class="width500">
                  <!-- <el-col :span="12"> -->
                  <!-- <el-form-item label="最低折扣" prop="minDiscount">
                    <el-input-number
                      style="width: 80%"
                      class="w100"
                      v-model="goodsForm.detail.minDiscount"
                      :disabled="!goodsForm.isModify"
                      :controls="false"
                    />
                    <div class="text-describe-color">说明: 90表示9折, 即90%</div>
                  </el-form-item> -->
                  <el-form-item label="出品部门" prop="departType">
                    <el-radio-group v-model="goodsForm.detail.departType" :disabled="!goodsForm.isModify">
                      <el-radio :label="0">与菜品分类一致</el-radio>
                      <el-radio :label="1">自定义出品部门</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="设置出品部门" prop="detail.departId" v-if="goodsForm.detail.departType === 1">
                    <el-select
                      v-model="goodsForm.detail.departId"
                      placeholder="请选择"
                      style="width: 80%"
                      :disabled="!goodsForm.isModify"
                    >
                      <el-option
                        v-for="category in departmentList"
                        :key="category.name"
                        :label="category.name"
                        :value="category.id"
                      />
                    </el-select>
                  </el-form-item>
                </div>
              </el-row>
            </div>

            <!-- 库存信息 -->
            <div>
              <div id="section4" class="fsize16" style="padding-left: 20px; color: #fdc31d">库存信息</div>
              <hr color="#f4f5f8" />
              <el-row :gutter="20">
                <div class="width500">
                  <el-form-item label="库存属性" prop="type">
                    <el-select v-model="goodsForm.detail.isGoods" :disabled="isGoodsMaterial || !goodsForm.isModify">
                      <el-option label="仅菜品" :value="0" />
                      <el-option label="也是原材料" :value="1" />
                      <el-option label="菜品即原料" :value="2" />
                    </el-select>
                  </el-form-item>

                  <div style="padding-left: 30px; font-size: 12px; color: #999999">
                    <div>注:1、仅菜品：不能成原材料，不可管理库存</div>
                    <div>2、也是原材料：是菜品且同步到原材料，可分开编辑菜品和原材料，仅原材料管理库存</div>
                    <div>3、菜品即原料：是菜品也是原材料，原材料不可编辑，菜品与原材料同一个库存。</div>
                  </div>

                  <el-form-item v-if="goodsForm.detail.isGoods === 2" label="库存数量" style="margin-top: 20px" prop="quantity">
                    <el-input-number
                      style="width: 100%"
                      v-model="goodsForm.detail.quantity"
                      :min="0"
                      :controls="false"
                    ></el-input-number>
                  </el-form-item>
                </div>

                <div v-if="goodsForm.detail.isGoods" class="width500">
                  <el-form-item label="原料类别" prop="detail.goodsCategoryId">
                    <div class="flx-default w100">
                      <el-tree-select
                        :disabled="!goodsForm.isModify"
                        node-key="value"
                        class="w100"
                        v-model="goodsForm.detail.goodsCategoryId"
                        :data="waresCategory"
                        :render-after-expand="false"
                        check-strictly
                      />
                    </div>
                  </el-form-item>
                </div>
              </el-row>
            </div>
          </el-tab-pane>

          <!-- <el-tab-pane label="辅助信息" name="second"> </el-tab-pane> -->

          <el-tab-pane v-if="goodsForm.type !== 2" label="菜品做法" name="third" style="min-height: 70vh">
            <!-- 普通菜 -->
            <!-- 😊😊😊😊😊😊套菜不显示菜品做法 -->
            <div style="width: 1000px" v-if="goodsForm.type !== 2">
              <el-form-item label="做法：">
                <div class="add-table-box" v-if="goodsForm.tasklist.length > 0">
                  <el-table border :data="goodsForm.tasklist">
                    <el-table-column type="index" label="序号" width="68"></el-table-column>
                    <el-table-column prop="taskName" label="做法名称"></el-table-column>
                    <el-table-column prop="taskPrice" label="变价金额">
                      <template #default="scope">
                        <span>{{ scope.row.taskPrice === 0 ? "免费" : scope.row.taskPrice }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column prop="selectType" label=" 是否必选（之一）">
                      <template #default="scope">
                        <el-switch
                          v-model="scope.row.selectType"
                          :active-value="1"
                          :inactive-value="0"
                          @change="(event:any) => onSelectType(event, scope.$index)"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column prop="isDefault" label="默认推荐">
                      <template #default="scope">
                        <el-checkbox v-model="scope.row.isDefault" :disabled="scope.row.selectType === 1" />
                      </template>
                    </el-table-column>
                    <el-table-column label="操作">
                      <template #default="scope">
                        <el-button type="danger" @click="deleteTaskRow(scope.$index, 'tasklist')" :disabled="!goodsForm.isModify">
                          删除
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
                <div>
                  <el-button type="primary" @click="openSelectTable('做法选择', 0)" :disabled="!goodsForm.isModify">
                    添加做法
                  </el-button>
                </div>
              </el-form-item>
              <!-- 菜品做法 end -->
            </div>
            <div v-else>套菜暂无菜品做法</div>

            <!-- 普通菜 end -->
          </el-tab-pane>

          <el-tab-pane v-if="goodsForm.type !== 2" label="菜品加料" name="fourth" style="min-height: 70vh">
            <div style="width: 1000px" v-if="goodsForm.type !== 2">
              <!-- 菜品加料 -->
              <el-form-item label="加料：">
                <div class="add-table-box" v-if="goodsForm.feedlist.length > 0">
                  <el-table border :data="goodsForm.feedlist">
                    <el-table-column type="index" label="序号" width="68"></el-table-column>
                    <el-table-column prop="feedName" label="做法名称"></el-table-column>
                    <el-table-column prop="feedPrice" label="变价金额">
                      <template #default="scope">
                        <span>{{ scope.row.feedPrice === 0 ? "免费" : scope.row.feedPrice }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column prop="isDefault" label="默认推荐">
                      <template #default="scope">
                        <el-checkbox v-model="scope.row.isDefault" />
                      </template>
                    </el-table-column>
                    <el-table-column label="操作">
                      <template #default="scope">
                        <el-button type="danger" @click="deleteTaskRow(scope.$index, 'feedlist')" :disabled="!goodsForm.isModify">
                          删除
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
                <div>
                  <el-button type="primary" @click="openSelectTable('加料选择', 0)" :disabled="!goodsForm.isModify">
                    添加加料
                  </el-button>
                </div>
              </el-form-item>
              <!-- 菜品加料 end -->
            </div>
            <div v-else>套菜暂无菜品加料</div>
          </el-tab-pane>

          <!-- 菜品分组start -->
          <el-tab-pane v-if="goodsForm.type !== 2" label="配菜管理" name="group" style="min-height: 70vh">
            <div style="width: 1200px" v-if="goodsForm.type !== 2">
              <!-- 菜品加料 -->
              <el-form-item label="分组：" prop="grouplist">
                <div class="add-table-box" v-if="goodsForm.grouplist.length > 0">
                  <el-table border :data="goodsForm.grouplist">
                    <el-table-column type="index" label="序号" width="68" />
                    <el-table-column prop="name" label="分组名称" width="150" />

                    <el-table-column label="关联菜品" width="250">
                      <template #default="{ row }">
                        <div class="tab-list">
                          <el-tag style="margin-right: 5px" type="warning" v-for="item in row.detailList" :key="item.id">{{
                            item.name
                          }}</el-tag>
                        </div>
                      </template>
                    </el-table-column>

                    <el-table-column prop="collectType" label="收取金额方式" width="150">
                      <template #default="{ row, $index }">
                        <el-select v-if="goodsForm.grouplist[$index].selectType === 2" v-model="row.collectType">
                          <el-option v-for="item in collectTypeList" :key="item.value" :label="item.label" :value="item.value">
                          </el-option>
                        </el-select>
                      </template>
                    </el-table-column>

                    <el-table-column prop="selectType" label="可选数量">
                      <template #default="{ row, $index }">
                        <div class="select-column">
                          <el-select v-model="row.selectType" @change="onSelectCount($event, $index)">
                            <el-option v-for="item in selectCountList" :key="item.value" :label="item.label" :value="item.value">
                            </el-option>
                          </el-select>

                          <el-input
                            oninput="value=value.replace(/[^0-9.]/g,'')"
                            v-if="row.selectType !== 1"
                            v-model="row.minQuantity"
                            style="max-width: 100px; margin-left: 10px"
                          >
                            <template v-if="row.selectType === 2" #append>份</template>
                          </el-input>
                          {{ row.selectType === 3 ? " ~ " : "" }}
                          <el-input-number
                            v-if="row.selectType === 3"
                            v-model="row.maxQuantity"
                            :controls="false"
                          ></el-input-number>
                        </div>
                        <div>
                          <el-checkbox v-if="row.selectType === 3" v-model="row.isSelectSame"> 组内配菜不可重复选择 </el-checkbox>
                        </div>
                      </template>
                    </el-table-column>

                    <el-table-column label="操作" width="100">
                      <template #default="scope">
                        <el-button
                          type="danger"
                          @click="deleteTaskRow(scope.$index, 'grouplist')"
                          :disabled="!goodsForm.isModify"
                        >
                          删除
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
                <div>
                  <el-button type="primary" @click="openSelectTable('分组选择', 0)" :disabled="!goodsForm.isModify">
                    添加分组
                  </el-button>
                </div>
              </el-form-item>
            </div>
            <div v-else>套菜暂无配菜信息</div>
          </el-tab-pane>
          <!-- 菜品分组end -->

          <!-- 其他信息 -->
          <el-tab-pane label="其他信息" name="fifth" style="min-height: 70vh">
            <!-- <h4 id="section4" class="fsize16">其他信息</h4> -->
            <el-row>
              <el-col>
                <el-form-item label="支持业务" prop="businessObject">
                  <el-checkbox-group v-model="goodsForm.businessObject" :disabled="!goodsForm.isModify">
                    <el-checkbox :label="1">堂食</el-checkbox>
                    <el-checkbox :label="2">外卖</el-checkbox>
                    <el-checkbox :label="3">自提</el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
                <!-- <el-form-item label="称重菜" prop="weighType">
                  <el-radio-group v-model="goodsForm.detail.weighType" :disabled="!goodsForm.isModify">
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="0">否</el-radio>
                  </el-radio-group>
                </el-form-item> -->
                <el-form-item label="菜品状态" prop="sellStatus">
                  <el-radio-group v-model="goodsForm.sellStatus" :disabled="!goodsForm.isModify">
                    <el-radio :label="im.value" v-for="im in sales" :key="im.value">{{ im.label }}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="10">
                <el-form-item label="微点餐状态" prop="mallStatus">
                  <el-radio-group v-model="goodsForm.mallStatus" :disabled="!goodsForm.isModify">
                    <el-radio :label="item.value" v-for="item in mall" :key="item.value">{{ item.label }}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="10">
                <el-form-item label="收银端临时改价" prop="isChangePrice">
                  <el-radio-group v-model="goodsForm.detail.isChangePrice" :disabled="!goodsForm.isModify">
                    <el-radio :label="true">允许</el-radio>
                    <el-radio :label="false">不允许</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="10">
                <el-form-item label="收银端手动打折" prop="isDiscount">
                  <el-radio-group v-model="goodsForm.detail.isDiscount" :disabled="!goodsForm.isModify">
                    <el-radio :label="true">允许</el-radio>
                    <el-radio :label="false">不允许</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="10">
                <!-- 
                  <el-form-item label="出品部门" prop="departType">
                  <el-radio-group v-model="goodsForm.detail.departType" :disabled="!goodsForm.isModify">
                    <el-radio :label="0">与菜品分类一致</el-radio>
                    <el-radio :label="1">自定义出品部门</el-radio>
                  </el-radio-group>
                </el-form-item> 
                <el-form-item label="设置出品部门" prop="detail.departId" v-if="goodsForm.detail.departType === 1">
                  <el-select
                    v-model="goodsForm.detail.departId"
                    placeholder="请选择"
                    style=""
                    :disabled="!goodsForm.isModify"
                  >
                    <el-option
                      v-for="category in departmentList"
                      :key="category.name"
                      :label="category.name"
                      :value="category.id"
                    />
                  </el-select>
                </el-form-item>
              -->

                <el-form-item label="数字助记码" prop="helpCode">
                  <el-input
                    v-model="goodsForm.detail.helpCode"
                    placeholder="请输入数字助记码"
                    clearable
                    :disabled="!goodsForm.isModify"
                  ></el-input>
                </el-form-item>
                <el-form-item label="拼音助记码" prop="pinYin">
                  <el-input v-model="goodsForm.detail.pinYin" placeholder="自动生成" clearable disabled></el-input>
                </el-form-item>
                <el-form-item label="保质期" prop="warrantyValue">
                  <el-input
                    class="w100"
                    v-model="goodsForm.detail.warrantyValue"
                    :controls="false"
                    :disabled="!goodsForm.isModify"
                  >
                    <template #append>
                      <el-select v-model="goodsForm.detail.warrantyType" style="width: 78px">
                        <el-option v-for="unit in timeUnit" :label="unit.label" :value="unit.value" :key="unit.label" />
                      </el-select>
                    </template>
                  </el-input>
                </el-form-item>
                <el-form-item label="组织机构" prop="organizationId" v-if="corpId === 0">
                  <el-select
                    clearable
                    v-model="goodsForm.organizationId"
                    placeholder="请选择"
                    style=""
                    :disabled="!goodsForm.isModify"
                  >
                    <el-option
                      v-for="category in organization"
                      :key="category.name"
                      :label="category.name"
                      :value="category.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- <el-row>
              <el-col :span="10">
                <el-form-item label="菜品起售份数" prop="upSell">
                  <el-input-number
                    class="w100"
                    v-model="goodsForm.detail.upSell"
                    :controls="false"
                    :disabled="!goodsForm.isModify"
                  />
                </el-form-item>
              </el-col>
            </el-row> -->
            <el-row>
              <el-col :span="10">
                <el-form-item label="增量售卖数" prop="addSell">
                  <el-input-number
                    class="w100"
                    v-model="goodsForm.detail.addSell"
                    :disabled="!goodsForm.isModify"
                    :controls="false"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="10">
                <!-- <el-form-item label="最低折扣" prop="minDiscount">
                  <el-input-number
                    class="w100"
                    v-model="goodsForm.detail.minDiscount"
                    :disabled="!goodsForm.isModify"
                    :controls="false"
                  />
                  <div class="text-describe-color">说明: 90表示9折, 即90%</div>
                </el-form-item> -->
                <el-form-item label="会员积分" prop="pointValue">
                  <el-input type="number" :min="0" v-model.number="goodsForm.detail.pointValue">
                    <template #append>
                      <el-select v-model="goodsForm.detail.pointType" style="width: 150px">
                        <el-option label="分(固定积分)" :value="1" />
                        <el-option label="%(销售额百分比)" :value="2" />
                      </el-select>
                    </template>
                  </el-input>
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                  <el-input-number
                    class="w100"
                    v-model="goodsForm.detail.sort"
                    :disabled="!goodsForm.isModify"
                    :controls="false"
                  />
                </el-form-item>

                <!-- 仓库 -->
                <el-form-item label="选择仓库" prop="sort">
                  <el-select v-model="goodsForm.detail.houseId" :disabled="!goodsForm.isModify">
                    <el-option v-for="item in storeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          <!-- 其他信息 end -->
          <!-- 手机端展示 -->
          <el-tab-pane label="手机端展示" name="sixth" style="min-height: 70vh">
            <!-- <h4 id="section6" class="fsize16">手机端展示</h4> -->
            <el-form-item label="菜品图片" prop="image">
              <UploadImg v-model:image-url="goodsForm.detail.image" :file-size="3" :disabled="!goodsForm.isModify">
                <template #empty>
                  <el-icon><Picture /></el-icon>
                </template>
                <template #tip> 图片大小不能超过 3M，建议上传 1 : 1 比例图片(例如：170 * 170) </template>
              </UploadImg>
            </el-form-item>
            <!-- <el-row>
              <el-col :span="10">
                <el-form-item label="手机点餐端展示" prop="isShow">
                  <el-radio-group v-model="goodsForm.detail.isShow" :disabled="!goodsForm.isModify">
                    <el-radio :label="true">否</el-radio>
                    <el-radio :label="false">是</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row> -->
            <el-row>
              <el-col :span="10">
                <el-form-item label="菜品描述" prop="remark">
                  <el-input
                    v-model="goodsForm.detail.remark"
                    placeholder="最多50字,在手机点餐端展示"
                    clearable
                    :disabled="!goodsForm.isModify"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- <el-row>
              <el-col :span="10">
                <el-form-item label="菜品详细描述" prop="remarkDetail">
                  <el-input
                    v-model="goodsForm.detail.remarkDetail"
                    placeholder=""
                    type="textarea"
                    :disabled="!goodsForm.isModify"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row> -->

            <el-row>
              <el-col :span="10">
                <el-form-item label="移动端菜品介绍" prop="introduce">
                  <WangEditor v-model:value="goodsForm.detail.introduce" height="300px" />
                  <div style="color: #999999">活动说明：上传图片后建议点击图片 100% 进行适配</div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          <!-- 手机端展示 end -->
        </el-tabs>
      </el-form>
    </div>
    <SelectTable @selected-list="handleSelectedList" ref="selectTableRef" />
    <CategoryDialog ref="categoryDialogRef" />
    <!-- 分组弹出层 -->
    <LaiDialog ref="laiDialogRef" @selected-list="onSelectGroup"></LaiDialog>
  </div>
</template>

<script setup lang="ts" name="GoodsAdd">
import { ref, reactive, onMounted, watch, watchEffect } from "vue";
import { useRouter, useRoute } from "vue-router";
import UploadImg from "@/components/Upload/Img.vue";
import SelectTable from "@/components/SelectTreeData/index.vue";
import CategoryDialog from "@/views/goods/components/CategoryDialog.vue";
import { addFoodCategory, getGoodsGroupListAPI } from "@/api/modules/goods";
import { getWaresCategoryList, getStorehouseList } from "@/api/modules/inventory"; // 原料类别
import {
  getFoodtaskList,
  getFoodtaskCategory,
  getFoodFeedCategory,
  getFoodFeedList,
  createFood,
  editFood,
  getFoodDedail,
  getFoodCategoryList,
  getGoodsSingleItem
} from "@/api/modules/goods";
import { useSelectStore } from "@/stores/modules/dict";
import { Delete, Plus, Bottom, Top, Minus, CircleCheck, CircleClose } from "@element-plus/icons-vue";
import type { FormInstance } from "element-plus";
import { getOrganizationList } from "@/api/modules/operation";
import { replaceArrayItems, transformCategories } from "@/utils";
import { Goods, Member } from "@/api/interface";
import { getDepartMentList } from "@/api/modules/operation";
import WangEditor from "@/components/WangEditor/index.vue";
import radio from "@/assets/icons/radio.svg";
import unRadio from "@/assets/icons/unRadio.svg";
import LaiDialog from "@/components/lai-dialog/index.vue";
import { collectTypeList, selectCountList } from "@/utils/serviceDict";
import { getMemberGradeList } from "@/api/modules/member";

const router = useRouter();
const route = useRoute();

const goodsForm = reactive<any>({
  id: 0,
  corpId: 0,
  storeId: 0,
  isModify: true,
  foodTypeId: null,
  type: 1,
  number: "123",
  name: "",
  byName: "",
  businessType: "",
  mallStatus: 1,
  sellStatus: 1,
  specFlag: true,
  foodSpecId: 0,
  isDelete: true,
  organizationId: null,
  statusText: "",
  foodCategoryName: "",
  foodTypeName: "",
  foodSpecName: "",
  businessObject: [1, 2, 3],
  detail: {
    isGoods: 0, //是否是原料分类
    goodsCategoryId: "", // 原料分类id
    foodId: 0,
    corpId: 0,
    storeId: 0,
    isHeft: true,
    helpCode: "",
    pinYin: "",
    warrantyValue: 1,
    warrantyType: 0,
    isPrint: true,
    gearOpening: "",
    isChangePrice: true,
    isDiscount: true,
    minDiscount: 0,
    weighType: 0,
    upSell: 0,
    departType: 0,
    addSell: 0,
    division: "",
    image: "",
    isShow: true,
    subscript: "",
    remark: "",
    remarkDetail: "",
    pointValue: 0,
    pointType: 1,
    houseId: 0,
    introduce: "",
    quantity: 0
  },
  speclist: [
    {
      id: 0,
      corpId: 0,
      storeId: 0,
      foodId: 0,
      code: "",
      // 修改规格默认名称
      // specName: "标准",
      specName: "份",
      onLine: true,
      isShare: true,
      isDelete: true,
      foodShopPriceId: 0,
      isDefault: true,
      posPrice: 0,
      vipPrice: 0,
      purPrice: 0,
      rmoPrice: 0,
      isSelected: true,
      isExclusive: true,
      name: "",
      price: 0,
      gradePriceList: []
    }
  ],
  tasklist: [],
  feedlist: [],
  grouplist: [],
  packlist: [
    {
      id: 0,
      foodId: 0,
      corpId: 0,
      storeId: 0,
      name: "",
      selectType: 2,
      plateType: 0,
      quantityStar: 1,
      quantityEnd: 1,
      isSelectSame: false,
      isDelete: true,
      packdetails: []
    }
  ]
});
// 测试测试
const copyGoodsForm = JSON.parse(JSON.stringify(goodsForm));

watch(
  () => goodsForm.packlist,
  val => {
    val.forEach((v: any) => {
      v.quantityStar = v.packdetails.length;
    });
  },
  { deep: true, immediate: true }
);

// 一下监听连个数据。先使用computed进行计算
// 计算属性，可以用来组合两个数据
// computed(() => {
//   return `${goodsForm.type} ${goodsForm.detail.isGoods}`;
// });
watchEffect(() => {
  // 有id时查回来的数据不能清空
  if ((goodsForm.type === 2 || goodsForm.detail.isGoods === 2) && !route.query.id) {
    goodsForm.speclist = [
      {
        id: 0,
        corpId: 0,
        storeId: 0,
        foodId: 0,
        code: "",
        // 修改规格默认名称
        // specName: "标准",
        specName: "份",
        onLine: true,
        isShare: true,
        isDelete: true,
        foodShopPriceId: 0,
        isDefault: true,
        posPrice: 0,
        vipPrice: 0,
        purPrice: 0,
        rmoPrice: 0,
        isSelected: true,
        isExclusive: true,
        name: "",
        price: 0,
        gradePriceList:
          memberList.value.length > 0
            ? memberList.value.map((v: Member.ResMemberGradeList) => {
                return {
                  gradeId: v.id,
                  id: 0,
                  name: v.title,
                  price: 0
                };
              })
            : []
      }
    ];
  }
});
// 获取仓库
const storeList = ref<any[]>([]);
// const defaultHouserId = ref("");
const onShowStore = async () => {
  const res = await getStorehouseList({});
  storeList.value = res.data.list;
  storeList.value.forEach(v => {
    if (v.isDefault) {
      goodsForm.detail.houseId = v.id;
    }
  });
};

const foodType = ref<any>([]);
const timeUnit = ref<any>([]);
const organization = ref<any>([]);
const ruleFormRef = ref<FormInstance>();
const isEdit = ref(false);
const collocation = ref<any>([]);
const sales = ref<any>([]);
const mall = ref<any>([]);

const activeName = ref("first");

const rules = reactive({
  name: [{ required: true, message: "请填写菜品名称" }],
  foodTypeId: [{ required: true, message: "请选择菜品分类" }],
  detail: {
    upSell: [{ required: true, message: "起售数量不能为空" }],
    departId: [{ required: true, message: "请选择出品部门" }],
    goodsCategoryId: [
      {
        validator: (rule: any, value: any, callback: Function) => {
          if (goodsForm.detail.isGoods && goodsForm.detail.goodsCategoryId === "") {
            callback(new Error("请选择一项原料"));
          } else {
            callback();
          }
        }
      }
    ]
  },
  businessObject: [{ required: true, message: "支持业务必选" }],
  grouplist: [
    {
      validator(rule: any, value: any[], callback: Function) {
        const arr: number[] = [];
        goodsForm.grouplist.forEach((v: any) => {
          arr.push(...v.foodspecIds);
          // arr.push(...v.foodspecIds);
        });
        const newArr = new Set(arr);

        if (arr.length > newArr.size) {
          callback(new Error("本组与其他分组配菜重复"));
        }

        if (
          goodsForm.grouplist.some((v: any) => {
            if (v.selectType === 2 && !v.minQuantity) return true;
            if (v.selectType === 3 && (!v.minQuantity || !v.maxQuantity)) return true;
            return false;
          })
        ) {
          callback(new Error("请输入正确的值"));
        }
        callback();
      }
    }
  ]
});

const setSpecDefault = (ix: number) => {
  goodsForm.speclist = goodsForm.speclist.map((spec: any) => {
    spec.isDefault = false;
    return spec;
  });
  goodsForm.speclist[ix].isDefault = true;
};

const onSelectType = (val: number, index: number) => {
  if (val === 1) {
    goodsForm.tasklist[index].isDefault = true;
  }
};

const deleteSpecRow = (index: number, pix: number) => {
  if (pix === -1) {
    goodsForm.speclist.splice(index, 1);
  } else {
    goodsForm.packlist[pix].packdetails.splice(index, 1);
  }
};

const delPackage = (index: number) => {
  if (goodsForm.packlist.length > 1) {
    goodsForm.packlist.splice(index, 1);
  }
};

const selectTableRef = ref<InstanceType<typeof SelectTable> | null>(null);
const laiDialogRef = ref<InstanceType<typeof LaiDialog> | null>(null);
const openSelectTable = (title: string, ix: number) => {
  if (title === "分组选择") {
    laiDialogRef.value!.acceptParams({
      columns: [
        { type: "selection", width: 80 },
        {
          prop: "name",
          label: "菜品分组",
          align: "left"
        },
        { prop: "desc", label: "描述", width: 200 },
        { prop: "count", label: "关联菜品数量", width: 200 }
      ],
      title,
      idName: "name",
      api: getGoodsGroupListAPI,
      selTags: goodsForm.grouplist
        ? goodsForm.grouplist.map((i: any) => {
            return { id: i.groupId, name: i.name };
          })
        : []
    });
    return;
  }

  const params = {
    title,
    isView: false,
    index: ix,
    mate: title === "菜品选择" ? "foodSpecId" : "id",
    selTags:
      title === "做法选择"
        ? goodsForm.tasklist.map((i: any) => {
            return { id: i.taskId, name: i.taskName };
          })
        : title === "加料选择"
        ? goodsForm.feedlist.map((i: any) => {
            return { id: i.feedId, name: i.feedName };
          })
        : title === "菜品选择"
        ? goodsForm.packlist[ix].packdetails.map((i: any) => {
            i.id = i.foodSpecId;
            i.name = i.foodName;
            return i;
          })
        : [],
    columns:
      title === "做法选择"
        ? [
            { type: "selection", width: 80 },
            { prop: "name", label: "做法名称", align: "left" },
            { prop: "price", label: "变价金额" }
          ]
        : title === "加料选择"
        ? [
            { type: "selection", width: 80 },
            { prop: "name", label: "加料名称", align: "left" },
            { prop: "price", label: "加料价格" }
          ]
        : title === "菜品选择"
        ? [
            { type: "selection", width: 80 },
            { prop: "name", label: "菜品名称", align: "left" },
            { prop: "foodTypeName", label: "分类", width: 120 },
            { prop: "foodSpecName", label: "规格", width: 100 },
            { prop: "posPrice", label: "菜品价格", width: 100 }
          ]
        : undefined,
    idName:
      title === "做法选择"
        ? "taskTypeId"
        : title === "加料选择"
        ? "feedTypeId"
        : title === "菜品选择"
        ? "foodCategoryId"
        : undefined,
    treeApi:
      title === "做法选择"
        ? getFoodtaskCategory
        : title === "加料选择"
        ? getFoodFeedCategory
        : title === "菜品选择"
        ? getFoodCategoryList
        : undefined,
    api:
      title === "做法选择"
        ? getFoodtaskList
        : title === "加料选择"
        ? getFoodFeedList
        : title === "菜品选择"
        ? getGoodsSingleItem
        : undefined
  };
  selectTableRef.value?.acceptParams(params);
};
// 选中分组
const onSelectGroup = (e: { list: any; title: string }) => {
  console.log(e, "wewwww");
  let list = e.list.map((im: any) => {
    // return { ...im,id:0, groupId: im.id, selectType: 1 };
    return {
      name: im.name,
      groupId: im.id,
      detailList: im.detailList,
      selectType: 1,
      foodspecIds: im.foodspecIds
    };
  });
  // console.log(list);

  goodsForm.grouplist = replaceArrayItems(list, goodsForm.grouplist, "groupId");
};

const onAddSpecItem = () => {
  goodsForm.speclist.push({
    isDefault: false,
    // 名字修改
    // specName: `规格${goodsForm.speclist.length + 1}`,
    specName: `份`,
    id: 0,
    corpId: 0,
    storeId: 0,
    foodId: 0,
    code: "",
    onLine: true,
    isShare: true,
    isDelete: true,
    foodShopPriceId: 0,
    posPrice: 0,
    vipPrice: 0,
    purPrice: 0,
    rmoPrice: 0,
    isSelected: true,
    isExclusive: true,
    name: "",
    price: 0,
    gradePriceList:
      memberList.value.length > 0
        ? memberList.value.map((v: Member.ResMemberGradeList) => {
            return {
              gradeId: v.id,
              id: 0,
              name: v.title,
              price: 0
            };
          })
        : []
  });
};
const deleteTaskRow = (index: number, name: string) => {
  if (name === "tasklist") {
    goodsForm.tasklist.splice(index, 1);
  } else if (name === "feedlist") {
    goodsForm.feedlist.splice(index, 1);
  } else if (name === "grouplist") {
    goodsForm.grouplist.splice(index, 1);
  }
};
const handleSelectedList = (val: any) => {
  if (val.title === "做法选择") {
    if (val.list.length > 0) {
      let list = val.list.map((im: any) => {
        return {
          taskName: im.name,
          feedPrice: im.feedPrice,
          selectType: 0,
          minQuantity: 0,
          maxQuantity: 0,
          taskPrice: im.price,
          taskId: im.id
        };
      });
      goodsForm.tasklist = replaceArrayItems(list, goodsForm.tasklist, "taskId");
    }
  } else if (val.title === "加料选择") {
    if (val.list.length > 0) {
      let list = val.list.map((im: any) => {
        return {
          feedName: im.name,
          feedPrice: im.price,
          selectType: 0,
          minQuantity: 0,
          maxQuantity: 0,
          feedId: im.id
        };
      });
      goodsForm.feedlist = replaceArrayItems(list, goodsForm.feedlist, "feedId");
    }
  } else if (val.title === "菜品选择") {
    if (val.list.length > 0) {
      let list = val.list.map((im: any) => {
        return {
          quantity: 1,
          foodName: im.name,
          specName: im.foodSpecName,
          foodSpecId: im.foodSpecId,
          setPrice: im.posPrice,
          foodId: im.id
        };
      });
      goodsForm.packlist[val.index].packdetails = replaceArrayItems(list, goodsForm.packlist[val.index].packdetails, "foodId");
    }
  }
};
const categoryDialogRef = ref<InstanceType<typeof CategoryDialog> | null>(null);
const openCategoryDialog = (title: string, row: Partial<Goods.ResGoodsCategoryList> = {}) => {
  // 打开新增菜品的弹出层
  const params = {
    title,
    row: { ...row },
    isView: false,
    api: addFoodCategory,
    getTableList: getFCategoryList
  };
  categoryDialogRef.value?.acceptParams(params);
};

const getFCategoryList = () => {
  // getFoodCategoryList({ pageNum: 1, pageSize: 9999, listType: goodsForm.isModify ? 0 : 1 }).then(res => {
  getFoodCategoryList({ pageNum: 1, pageSize: 9999, listType: route.query.type ? 1 : 0 }).then(res => {
    foodType.value = transformCategories(res.data.list, "name", "id", true);
  });
};

const categoryId = ref<number>(0);
const onSubmit = (type: string) => {
  ruleFormRef.value!.validate(async valid => {
    categoryId.value = goodsForm.foodTypeId;
    if (!valid) return;
    try {
      if (!goodsForm.detail.weighType) {
        goodsForm.detail.upSell = Math.round(goodsForm.detail.upSell);
      } else {
        goodsForm.detail.upSell = parseFloat(goodsForm.detail.upSell.toFixed(3));
      }
      if (isEdit.value) {
        await editFood(goodsForm).then(() => {
          ruleFormRef.value!.resetFields();
          if (type === "create") {
            router.push({
              path: `/goods/goods-add-copy`
            });
            Object.keys(goodsForm).forEach(key => {
              if (copyGoodsForm.hasOwnProperty(key) && key !== "foodTypeId") {
                goodsForm[key] = copyGoodsForm[key];
              }
              if (key === "speclist") {
                goodsForm[key] = [
                  {
                    id: 0,
                    corpId: 0,
                    storeId: 0,
                    foodId: 0,
                    code: "",
                    // 修改规格默认名称
                    // specName: "标准",
                    specName: "份",
                    onLine: true,
                    isShare: true,
                    isDelete: true,
                    foodShopPriceId: 0,
                    isDefault: true,
                    posPrice: 0,
                    vipPrice: 0,
                    purPrice: 0,
                    rmoPrice: 0,
                    isSelected: true,
                    isExclusive: true,
                    name: "",
                    price: 0,
                    gradePriceList:
                      memberList.value.length > 0
                        ? memberList.value.map((v: Member.ResMemberGradeList) => {
                            return {
                              gradeId: v.id,
                              id: 0,
                              name: v.title,
                              price: 0
                            };
                          })
                        : []
                  }
                ];
              }
            });
          } else {
            console.log(categoryId.value);

            router.push({
              path: "/goods/goods-list",
              query: {
                upList: true,
                categoryId: categoryId.value
              }
            });
          }
        });
      } else {
        await createFood(goodsForm).then(() => {
          ruleFormRef.value!.resetFields();
          if (type === "create") {
            Object.keys(goodsForm).forEach(key => {
              if (copyGoodsForm.hasOwnProperty(key) && key !== "foodTypeId") {
                goodsForm[key] = copyGoodsForm[key];
              }
              if (key === "speclist") {
                goodsForm[key] = [
                  {
                    id: 0,
                    corpId: 0,
                    storeId: 0,
                    foodId: 0,
                    code: "",
                    // 修改规格默认名称
                    // specName: "标准",
                    specName: "份",
                    onLine: true,
                    isShare: true,
                    isDelete: true,
                    foodShopPriceId: 0,
                    isDefault: true,
                    posPrice: 0,
                    vipPrice: 0,
                    purPrice: 0,
                    rmoPrice: 0,
                    isSelected: true,
                    isExclusive: true,
                    name: "",
                    price: 0,
                    gradePriceList:
                      memberList.value.length > 0
                        ? memberList.value.map((v: Member.ResMemberGradeList) => {
                            return {
                              gradeId: v.id,
                              id: 0,
                              name: v.title,
                              price: 0
                            };
                          })
                        : []
                  }
                ];
              }
            });
          } else {
            router.push({
              path: "/goods/goods-list",
              query: {
                upList: true
              }
            });
          }
        });
      }
    } catch (error) {
      console.log(error);
    }
  });
};

const addPackGroup = () => {
  goodsForm.packlist.push({
    name: "",
    selectType: 2,
    plateType: 0,
    quantityStar: 1,
    quantityEnd: 1,
    isSelectSame: false,
    isDelete: true,
    packdetails: []
  });
};
// 编辑获取数据是判断是否原料，是原料禁用按钮
const isGoodsMaterial = ref(false);

const moveUp = (index: number) => {
  let arr = goodsForm.packlist;
  arr.splice(index - 1, 1, ...arr.splice(index, 1, arr[index - 1]));
};
const moveDown = (index: number) => {
  let arr = goodsForm.packlist;
  arr.splice(index, 1, ...arr.splice(index + 1, 1, arr[index]));
};
const departmentList = ref<any>([]);
watch(
  // 判断接口部门为自定义时给默认值
  () => goodsForm.detail.departType,
  newValue => {
    if (newValue) {
      if (goodsForm.id) {
        goodsForm.detail.departId = goodsForm.detail.departId;
      } else {
        goodsForm.detail.departId = departmentList.value[0].id;
      }
    } else {
      goodsForm.detail.departId = "";
    }
  },
  { immediate: true }
);

// 判断为套菜时禁用是否原来，并把原料修改为false
watch(
  () => goodsForm.type,
  newV => {
    if (newV === 2) {
      goodsForm.detail.isGoods = 0;
      isGoodsMaterial.value = true;
    } else {
      isGoodsMaterial.value = false;
    }
  },
  { immediate: true }
);

// 本地里面信息
const corpId = ref(0);
onMounted(async () => {
  const storage = JSON.parse(localStorage.getItem("my-user") as string);
  corpId.value = storage.store.corpId;

  const [foodTy, orz, department] = await Promise.all([
    getFoodCategoryList({ pageNum: 1, pageSize: 9999, listType: route.query.type ? 1 : 0 }),
    // getFoodCategoryList({ pageNum: 1, pageSize: 9999, listType: goodsForm.isModify ? 0 : 1 }),
    getOrganizationList(),
    getDepartMentList({ pageNum: 1, pageSize: 9999 }),
    onGetMemberList()
  ]);
  foodType.value = transformCategories(foodTy.data.list, "name", "id", true);
  organization.value = orz.data.list;
  departmentList.value = department.data.list;
  useSelectStore()
    .getDic("WarrantyType")
    .then(data => {
      timeUnit.value = data;
    });
  useSelectStore()
    .getDic("FoodPackSelectType")
    .then(data => {
      collocation.value = data;
    });
  useSelectStore()
    .getDic("SalesStatus")
    .then(data => {
      sales.value = data;
    });
  useSelectStore()
    .getDic("MallStatus")
    .then(data => {
      mall.value = data;
    });
  if (route.query.id) {
    isEdit.value = true;
    getFoodDedail({ id: route.query.id }).then((res: any) => {
      isGoodsMaterial.value = res.data.detail.isGoods;
      Object.keys(goodsForm).forEach(key => {
        if (res.data.hasOwnProperty(key)) {
          goodsForm[key] = res.data[key];
        }
      });
    });
  } else {
    goodsForm.foodTypeId =
      foodTy.data.list.length > 0 ? (+route.query!.foodCategoryId ? +route.query!.foodCategoryId : foodTy.data.list[0].id) : "";
    // goodsForm.organizationId = orz.data.list.length > 0 ? orz.data.list[0].id : "";
  }
  onShowStore();
});

// 监听数据菜品类型
const waresCategory = ref([]);
const onWaresCategoryList = async () => {
  const res = await getWaresCategoryList({});
  waresCategory.value = transformCategories(res.data, "name", "id", true);
};
watch(
  () => goodsForm.detail.isGoods,
  newValue => {
    if (newValue) {
      onWaresCategoryList();
    } else {
      // 当不是原料时原料id复原为空
      goodsForm.detail.goodsCategoryId = "";
    }
  }
);

// 切换菜品分组的可选数量方式
const onSelectCount = async (e: number, index: number) => {
  goodsForm.grouplist[index].collectType = null;
  goodsForm.grouplist[index].minQuantity = null;
  goodsForm.grouplist[index].maxQuantity = null;
  goodsForm.grouplist[index].isSelectSame = false;
  if (e === 2) {
    goodsForm.grouplist[index].collectType = 1;
  }
};

// 会员列表
const memberList = ref<Member.ResMemberGradeList[]>([]);

const onGetMemberList = async () => {
  const { data } = await getMemberGradeList({ pageNum: 1, pageSize: 999, discountType: 3 });
  console.log(data);
  memberList.value = data.list;
  if (!route.query.id) {
    goodsForm.speclist[0].gradePriceList = data.list.map((v: Member.ResMemberGradeList) => {
      return {
        gradeId: v.id,
        id: 0,
        name: v.title,
        price: 0
      };
    });
  }
};

const weightChange = (newValue: number) => {
  if (newValue) {
    goodsForm.detail.upSell = 0;
  } else {
    goodsForm.detail.upSell = 1;
  }
};
</script>

<style lang="scss" scoped>
@import "./index.scss";

// h4 {
//   // font-weight: 600;
// }
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
}
::v-deep .el-table__row .el-input-group__append {
  padding: 0 10px !important; /* 你想要的宽度 */
}

// ::v-deep .el-input__inner {
//   text-align: center;
// }
</style>
